from django.http import JsonResponse, Http404
from django.shortcuts import render, redirect
from django.urls import reverse_lazy
from django.views.generic import TemplateView, CreateView
from django.contrib.auth.decorators import login_required
from django.contrib.auth.mixins import LoginRequiredMixin

from .utils_v3 import Supervisor_Process_Managet_Class   as s_p_m_class

from .models import SupervisorHost, Supervisor_Process, Supervisor_Action_History

from .apps import  SupervisorDjConfig

app_name = SupervisorDjConfig.name






class Supervisor_Search_Mixin:
    def get_queryset(self, model):
        q = self.request.GET.get('q')
        if q:
            return model.objects.filter(processes__name__contains=q).select_related()
        return model.objects.all().select_related()


class supervisor_hostlist_class_view(LoginRequiredMixin, Supervisor_Search_Mixin, TemplateView):
    template_name = 'supervisor_dj/supervisor_dj_list.html'

    def get_context_data(self, **kwargs):
        self.request.app_name = app_name

        action_histtory = Supervisor_Action_History.objects.all()[:5]
        host_count = SupervisorHost.objects.count()
        process_count = Supervisor_Process.objects.count()
        data = {
            "action_histtory": action_histtory,
            "host_count": host_count,
            "process_count": process_count,
            "app_name": app_name,
        }
        q = self.request.GET.get('q')

        if q:
            # 是否有搜索内容
            data['processes_list'] = Supervisor_Process.objects.filter(name__contains=q)
            data['q'] = q
        else:
            data['process_host_list'] = SupervisorHost.objects.all()
        kwargs.update(data)
        return super().get_context_data(**kwargs)


@login_required
def start(request):
    """
    启动进程
        :param request:   ip action
        :return:
    """
    process_name = request.GET.get('process_name', None)
    ip = request.GET.get('ip', None)
    action = request.GET.get('action', None)
    if not ip or not action or not process_name:
        data = {"status_code": False, "msg": "必须传入process_name,ip,action参数"}
        return JsonResponse(data)

    super_class = s_p_m_class().start_or_stop(process_name=process_name, ip=ip, action=action)

    Supervisor_Action_History.objects.create(  # todo 放到队列中执行
        action_name="start", ip=ip,
        process_name=process_name,
        status_code=super_class["status_code"])
    return JsonResponse(super_class, )


@login_required
def stop(request):
    """
    停止进程
        :param ip, 进程名 、ip
        :return:
    """
    process_name = request.GET.get('process_name', None)
    ip = request.GET.get('ip', None)
    action = request.GET.get('action', None)
    if not ip or not action or not process_name:
        data = {"status_code": False, "msg": "必须传入process_name,ip,action参数"}
        return JsonResponse(data)
    super_class = s_p_m_class().start_or_stop(process_name=process_name, ip=ip, action=action)
    Supervisor_Action_History.objects.create(  # todo 放到队列中执行
        action_name="stop", ip=ip,
        process_name=process_name,
        status_code=super_class["status_code"])
    return JsonResponse(super_class, )


@login_required
def restart(request):
    """
    重启进程
        :param request: process_name , ip
        :return:
    """
    process_name = request.GET.get('process_name', None)
    ip = request.GET.get('ip', None)
    if not ip or not process_name:
        data = {"status_code": False, "msg": "必须传入process_name,ip,参数"}
        return JsonResponse(data)

    super_class = s_p_m_class().restart(process_name=process_name, ip=ip, )
    Supervisor_Action_History.objects.create(  # todo 放到队列中执行
        action_name="restart", ip=ip,
        process_name=process_name,
        status_code=super_class["status_code"])
    return JsonResponse(super_class, )


@login_required
def detail(request):
    """
    获取进程详情
        :param request:
        :return:
    """
    process_name = request.GET.get('process_name', None)
    ip = request.GET.get('ip', None)
    # todo 从数据库从查询数据不是最新的
    qs = Supervisor_Process.objects.filter(ip=ip, name=process_name)
    if not qs.exists():
        data = {f'进程信息:{process_name}-{ip}': '没有找到'}
        return JsonResponse(data)

    qs = qs.first().detail
    return JsonResponse(qs)


@login_required
def refresh_all_process(request):
    """
    刷新一台主机所有进程信息
        :param request: ip
        :return:
    """
    ip = request.GET.get('ip', None)
    if not ip:
        raise Http404("必须传入Ip")
    process_obj = s_p_m_class().get_processes_from_host(ip=ip)
    return JsonResponse(process_obj)


@login_required
def refresh_allhost_allprocess(request):
    """
    刷新所有主机所有进程
        :param request:
        :return:
    """
    res = s_p_m_class().refresh_allhost_allprocess()
    return JsonResponse(res)


class Add_Supervisor_Host_View(LoginRequiredMixin, CreateView):
    model = SupervisorHost
    fields = ("hostname", "ip", "port")
    success_url = reverse_lazy("supervisor_list")
    template_name = 'supervisor_dj/supervisor_add_host.html'
